const mongoose = require('mongoose');
const config = require('../config');
let connectionString='';
if(config.debug){
    connectionString = `mongodb://${config.devConfig.mongodb.host}:${config.devConfig.mongodb.port}/${config.devConfig.mongodb.db}`;
}else{
    connectionString = `mongodb://${config.devConfig.mongodb.host}:${config.devConfig.mongodb.port}/${config.devConfig.mongodb.db}`;
    //connectionString = `mongodb://${config.mongodb.usr}:${config.mongodb.pwd}@${config.mongodb.host}:${config.mongodb.port}/${config.mongodb.db}`;
}

const options = {
    // db: {
    //     native_parser: true
    // },
    // server: {
    //     auto_reconnect: true,
    //     poolSize: 5
    // },
    // 新添加的连接Url参数
    useNewUrlParser: true,
    // 新版API所有参数都是顶层参数，没有层级概念
    native_parser: true,
    auto_reconnect: true,
    poolSize: 5

};

mongoose.Promise = require('bluebird');
mongoose.set('useCreateIndex', true);
mongoose.connect(connectionString, options, (err, res)=> {
    if (err) {
        console.log(`[mongoose log] Error connecting to: ${connectionString} . ${err}`);
        return process.exit(1);
    } else {
        return console.log(`[mongoose log] Successfully connected to: ${connectionString}`);
    }
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'mongoose connection error:'));

db.once('open', function() {
    return console.log('mongoose open success');
});


module.exports = db;